import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import path from "node:path";
import { execSync } from "node:child_process";

// https://vitejs.dev/config/
export default defineConfig({
  // OSS部署配置 - 根据你的实际OSS域名和路径调整
  base: process.env.NODE_ENV === 'production' ? '/' : '/',
  server: {
    host: "0.0.0.0",
  },
  plugins: [react()],
  define: {
    __BUILD_INFO__: {
      time: new Date().toLocaleString(),
      branch: execSync("git rev-parse --abbrev-ref HEAD").toString().trim(),
    },
  },
  resolve: {
    alias: { "@": path.resolve(__dirname, "src") },
  },
  build: {
    // 优化构建配置以提升FCP
    rollupOptions: {
      output: {
        // 代码分割策略
        manualChunks: {
          // 将React相关库分离到单独的chunk
          'react-vendor': ['react', 'react-dom', 'react-router-dom'],
          // 将UI库分离
          'ui-vendor': ['antd', '@ant-design/icons'],
          // 将工具库分离
          'utils-vendor': ['axios', 'lodash', 'moment', 'clsx']
        },
        // OSS部署优化：确保资源文件名包含hash以支持缓存
        assetFileNames: 'assets/[name].[hash].[ext]',
        chunkFileNames: 'js/[name].[hash].js',
        entryFileNames: 'js/[name].[hash].js'
      }
    },
    // 启用CSS代码分割
    cssCodeSplit: true,
    // 优化chunk大小警告阈值
    chunkSizeWarningLimit: 1000,
    // 启用源码映射（仅开发环境）
    sourcemap: false,
    // 压缩配置
    minify: 'terser',
    terserOptions: {
      compress: {
        // 移除console
        drop_console: true,
        drop_debugger: true,
        // 移除未使用的代码
        pure_funcs: ['console.log', 'console.info', 'console.debug', 'console.warn']
      }
    }
  },
  // 优化依赖预构建
  optimizeDeps: {
    include: [
      'react',
      'react-dom',
      'react-router-dom',
      'antd',
      '@ant-design/icons',
      'axios',
      'lodash',
      'moment',
      'clsx'
    ]
  }
});
